package com.cnt.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;


import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TokenUtil {

    private static final long EXPIRATION_TIME = 864_000_000; // 10天
    private static final String SECRET_KEY = "okkkkkkkkkkkkkkk"; // 设置你自己的密钥
    // 存储用户的 Token
    private static final Map<Integer, String> userTokens = new ConcurrentHashMap<>();

    public static String generateToken(String userId) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .setSubject(userId)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    public static String getTokenFromRequest(HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        System.out.println("2"+token);
        if (token != null && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return null;
    }

    public static String getUserIdFromToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            return claims.getSubject();
        } catch (Exception e) {
            return null;
        }
    }

    // 保存用户的 Token
    public static void saveToken(int userId, String token) {
        userTokens.put(userId, token);
        System.out.println("保存后"+userTokens);
    }

    // 删除用户的 Token
    public static void removeToken(String token) {
        for (Map.Entry<Integer, String> entry : userTokens.entrySet()) {
            if (entry.getValue().equals(token)) {
                userTokens.remove(entry.getKey());
                break;
            }
        }
        System.out.println("删除后===》"+userTokens);
    }

    // 获取指定用户的 Token
    public static String getToken(int userId) {
        return userTokens.get(userId);
    }

}
